import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  RangePicker,
  Space,
  TypographyText
} from 'ant-design-vue'
import moment, { Moment } from 'moment'
import { defineComponent, ref } from 'vue'

import { commonMenuApi } from '@/apis'
import { IndexIconItem } from '@/apis/commonMenyTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import UploadFile from '@/components/UploadFile'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'

export default defineComponent({
  name: 'MinAppIcon',
  setup() {
    const { showConfirm } = useDialog()

    const showIconDialog = ref(false)
    const iconDialogLoading = ref(false)

    const showStyleDialog = ref(false)
    const styleDialogLoading = ref(false)

    const optionItemCur = ref({} as IndexIconItem)

    const statusOptions = [
      { label: '禁用', value: 0 },
      { label: '启用', value: 1 }
    ]
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '标题',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '分类',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: statusOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            title: '标题',
            field: 'name'
          },
          {
            title: '图标',
            field: 'img',
            width: 100,
            slots: {
              default: 'image'
            }
          },
          {
            title: '排序',
            field: 'sort'
          },
          {
            title: '副标题',
            field: 'showStyle',
            minWidth: 150
          },
          {
            title: '促销样式',
            field: 'promoteLabel',
            minWidth: 150
          },
          {
            title: '创建时间',
            field: 'createTime',
            minWidth: 200,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '状态',
            fixed: 'right',
            width: 100,
            slots: {
              default: 'status'
            }
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 200
          }
        ],

        proxyConfig: {
          props: {
            result: 'data'
          },
          ajax: {
            query: async () => {
              const data = await commonMenuApi.getIndexIconList()
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const modalTime = ref([] as any[])

    const disabledDate = (current: Moment) => {
      return current && current < moment().startOf('day')
    }

    //新增图标
    function addOrEditIcon(item) {
      if (!item) {
        optionItemCur.value = { status: false } as IndexIconItem
      } else {
        Object.assign(optionItemCur.value, item)
      }
      showIconDialog.value = true
    }

    async function addOrEditIconConfirm() {
      if (!optionItemCur.value.name) {
        message.error('请输入标题')
        return
      }
      if (!optionItemCur.value.img) {
        message.error('请选择图标')
        return
      }

      try {
        iconDialogLoading.value = true
        if (optionItemCur.value.id) {
          await commonMenuApi.editIndexIcon(optionItemCur.value)
        } else {
          await commonMenuApi.addIndexIcon(optionItemCur.value)
        }
        showIconDialog.value = false
        tableRef.value.refresh()
      } finally {
        iconDialogLoading.value = false
      }
    }

    //编辑活动样式
    function editStyle(item) {
      Object.assign(optionItemCur.value, item)
      modalTime.value = item.showStartTime
        ? [moment(item.showStartTime), moment(item.showEndTime)]
        : []
      showStyleDialog.value = true
    }

    async function editStyleConfirm() {
      if (!optionItemCur.value.name) {
        message.error('请输入副标题')
        return
      }
      if (!optionItemCur.value.img) {
        message.error('请输入促销样式')
        return
      }

      try {
        styleDialogLoading.value = true
        optionItemCur.value.showStartTime =
          modalTime.value.length > 0 ? modalTime.value[0].format('x') : ''
        optionItemCur.value.showEndTime =
          modalTime.value.length > 1 ? modalTime.value[1].format('x') : ''
        await commonMenuApi.editStyle(optionItemCur.value)
        showStyleDialog.value = false
        tableRef.value.refresh()
      } finally {
        styleDialogLoading.value = false
      }
    }

    //启用禁用
    function forbid(item) {
      showConfirm({
        content: item.status ? '确认启用该图标？' : '确认禁用该图标',
        onOk: async () => {
          try {
            await commonMenuApi.upDownIcon(item.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    return {
      tableRef,
      tableConfig,

      modalTime,

      showIconDialog,
      iconDialogLoading,
      showStyleDialog,
      styleDialogLoading,
      optionItemCur,
      disabledDate,
      addOrEditIcon,
      addOrEditIconConfirm,
      editStyle,
      editStyleConfirm,
      forbid
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            image: ({ row }) => <Image src={row.img}></Image>,
            toolbarButtons: () => (
              <Button
                type="primary"
                onClick={() => {
                  this.addOrEditIcon(null)
                }}
              >
                新增
              </Button>
            ),
            status: ({ row }) => {
              return (
                <Space>
                  {row.status ? (
                    <TypographyText type="danger">禁用</TypographyText>
                  ) : (
                    <TypographyText type="success">启用</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.addOrEditIcon(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.forbid(row)}
                >
                  {row.status ? '启用' : '禁用'}
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.editStyle(row)}
                >
                  活动样式
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showIconDialog}
          width={600}
          destroyOnClose
          title={this.optionItemCur.id ? '编辑' : '新增'}
          onOk={this.addOrEditIconConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'标题'} required>
              <Input
                placeholder={'请输入'}
                v-model:value={this.optionItemCur.name}
                style={{ width: '300px' }}
                maxlength={8}
                v-slots={{
                  suffix: () => (
                    <span>
                      {this.optionItemCur.name
                        ? this.optionItemCur.name.length
                        : 0}
                      /8
                    </span>
                  )
                }}
              />
            </FormItem>
            <FormItem label={'图标'} required>
              <UploadFile v-model={[this.optionItemCur.img, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'跳转链接'}>
              <Input
                placeholder={'请输入'}
                v-model:value={this.optionItemCur.redirectUrl}
                style={{ width: '400px' }}
              />
            </FormItem>
            <FormItem label={'排序'}>
              <InputNumber
                placeholder={'请输入'}
                v-model:value={this.optionItemCur.sort}
                style={{ width: '300px' }}
                min={1}
                maxlength={4}
              />
              <p style={{ marginTop: '10px', color: '#888' }}>
                请输入大于等于1的整数，值越小排前面
              </p>
            </FormItem>
            <FormItem label="状态" required>
              <RadioGroup v-model:value={this.optionItemCur.status}>
                <Radio value={false}>启用</Radio>
                <Radio value={true}>禁用</Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </Modal>

        <Modal
          v-model:visible={this.showStyleDialog}
          width={600}
          destroyOnClose
          title={'活动样式'}
          onOk={this.editStyleConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'副标题'}>
              <Input
                placeholder={'请输入'}
                v-model:value={this.optionItemCur.showStyle}
                style={{ width: '300px' }}
                maxlength={8}
                v-slots={{
                  suffix: () => (
                    <span>
                      {this.optionItemCur.showStyle
                        ? this.optionItemCur.showStyle.length
                        : 0}
                      /8
                    </span>
                  )
                }}
              />
            </FormItem>
            <FormItem label={'促销样式'}>
              <Input
                placeholder={'请输入'}
                v-model:value={this.optionItemCur.promoteLabel}
                style={{ width: '300px' }}
                maxlength={8}
                v-slots={{
                  suffix: () => (
                    <span>
                      {this.optionItemCur.promoteLabel
                        ? this.optionItemCur.promoteLabel.length
                        : 0}
                      /8
                    </span>
                  )
                }}
              />
            </FormItem>
            <FormItem label={'有效期'}>
              <Space>
                <RangePicker
                  disabledDate={this.disabledDate}
                  v-model:value={this.modalTime}
                  showTime={{
                    hideDisabledOptions: true,
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  }}
                  format={'YYYY-MM-DD HH:mm:ss'}
                  separator={'至'}
                  style={{ width: '400px' }}
                />
              </Space>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
